package com.asp.alumnisystem.fragment;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.asp.alumnisystem.base.BaseAdapter;
import com.asp.alumnisystem.base.BaseBean;
import com.asp.alumnisystem.base.BaseFragment;
import com.asp.alumnisystem.base.BasePresenter;
import com.asp.alumnisystem.base.IView;
import com.asp.alumnisystem.model.PageModel;
import com.asp.alumnisystem.utils.ListUtils;
import com.asp.alumnisystem.utils.ToastUtil;
import com.asp.alumnisystem.view.CustomRecyclerView;
import com.asp.alumnisystem.view.TitleBar;

import java.util.List;

/**
 * 首页展示信息的抽象Fragment
 */
public abstract class AspBaseFragment<T> extends BaseFragment implements CustomRecyclerView.RecyclerListener, IView<List<T>> {

    protected CustomRecyclerView recyclerView;
    protected PageModel pageModel = new PageModel();
    protected BaseAdapter adapter;
    protected BasePresenter presenter;

    @Override
    public BaseAdapter getBaseAdapter() {
        return adapter;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        recyclerView = new CustomRecyclerView(getContext());
        recyclerView.setListener(this);
        return recyclerView;
    }

    protected void setTitleStr(String str){
        TitleBar titleBar = recyclerView.getTitleBar();
        titleBar.setTitleStr(str);
        titleBar.setBackViewGone();
    }

    @Override
    public void loadDone(BasePresenter presenter) {
        super.loadDone(presenter);
        recyclerView.stopRefreshing();
    }

    @Override
    protected void viewGone() {
        super.viewGone();
        recyclerView.stopRefreshing();
    }

    @Override
    public void onRefresh(RecyclerView recyclerView) {
        pageModel.reset();
        presenter.work(pageModel);
    }

    @Override
    public void loadSuccess(BasePresenter presenter, BaseBean<List<T>> result) {
        if (result.success){
            if (pageModel.isFirstPage()){
                adapter.setList(result.data);
            }else{
                adapter.addList(result.data);
            }
            pageModel.setRequestCount(ListUtils.isNotNull(result.data) ? result.data.size() : 0);
        }else{
            ToastUtil.showShortToast(result.error);
            adapter.dataChange();
        }
    }

    @Override
    public void loadMore(RecyclerView recyclerView) {
        if (pageModel.isHaveNextAndToast(this)){
            presenter.work(pageModel);
        }
    }


}
